package service

import (
	"context"
	"encoding/json"
	"github.com/google/uuid"
	"time"
	"video-srv/basic/config"
	__ "video-srv/basic/proto/rpc"
	"video-srv/handler/model"
)

type VideoServer struct {
	__.UnimplementedVideoServer
}

func (s *VideoServer) PublishVideo(_ context.Context, in *__.PublishVideoReq) (*__.PublishVideoResp, error) {
	video := model.Video{
		UserId:   int(in.UserId),
		Title:    in.Title,
		Category: in.Category,
		Tags:     in.Tags,
		CoverUrl: in.CoverUrl,
		VideoUrl: in.VideoUrl,
	}
	err := video.PublishVideo(config.DB)
	if err != nil {
		return nil, err
	}
	return &__.PublishVideoResp{
		VideoId: int64(video.ID),
	}, nil
}
func (s *VideoServer) CheckVideo(_ context.Context, in *__.CheckVideoReq) (*__.CheckVideoResp, error) {
	checkVideo := model.CheckVideo{
		UserId:  int(in.UserId),
		VideoId: int(in.VideoId),
		Status:  int(in.Status),
	}
	err := checkVideo.CheckVideo(config.DB)
	if err != nil {
		return nil, err
	}
	var video model.Video
	err = video.UpdateVideoStatus(config.DB, int(in.VideoId), int(in.Status))
	if err != nil {
		return nil, err
	}
	videoStr, _ := json.Marshal(video)
	config.Rdb.Set(config.Ctx, "hotVideoList", videoStr, time.Hour)
	return &__.CheckVideoResp{
		CheckVideoId: int64(checkVideo.ID),
		VideoToken:   uuid.NewString(),
	}, nil
}

func (s *VideoServer) GetVideoListById(_ context.Context, in *__.GetVideoListByIdReq) (*__.GetVideoListByIdResp, error) {
	var video model.Video
	info, err := video.GetVideoListById(config.DB, int(in.VideoId))
	if err != nil {
		return nil, err
	}
	return &__.GetVideoListByIdResp{
		UserId:    info.UserId,
		Title:     info.Title,
		Category:  info.Category,
		Tags:      info.Tags,
		CoverUrl:  info.CoverUrl,
		VideoUrl:  info.VideoUrl,
		Status:    info.Status,
		CreatedAt: info.CreatedAt,
		Reason:    info.Reason,
	}, nil
}
